/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * CoRmPanel.java
 *
 * Created on 29/11/2011, 23:14:56
 */

package proj5labbd.graphics.comercial;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import proj5labbd.DBInterface;
import proj5labbd.graphics.abstractOpGraphics.OperationPanel;

/*
 * Painel de controle de remoção de dados na base de dados
 */
public class CoRmPanel extends OperationPanel {

    /** Creates new form CoRmPanel */
    public CoRmPanel(ComercialFrame frame, DBInterface dbInterface) {
        super(frame,dbInterface);
        initComponents();
        jbtRemove.addActionListener(new ComercialAction());
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jpnInsert = new javax.swing.JPanel();
        jlbTitulo = new javax.swing.JLabel();
        jtxtTitulo = new javax.swing.JTextField();
        jlbDept = new javax.swing.JLabel();
        jtxtDept = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtbRemove = new javax.swing.JTable();
        jbtRemove = new javax.swing.JButton();

        setBorder(javax.swing.BorderFactory.createTitledBorder("Remove"));
        addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                formMouseClicked(evt);
            }
        });
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                formComponentShown(evt);
            }
        });

        jpnInsert.setBorder(javax.swing.BorderFactory.createTitledBorder("Parâmetros de remoção"));

        jlbTitulo.setText("Título");

        jlbDept.setText("Departamento");

        javax.swing.GroupLayout jpnInsertLayout = new javax.swing.GroupLayout(jpnInsert);
        jpnInsert.setLayout(jpnInsertLayout);
        jpnInsertLayout.setHorizontalGroup(
            jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnInsertLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jtxtTitulo, javax.swing.GroupLayout.PREFERRED_SIZE, 224, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jlbTitulo))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jlbDept)
                    .addComponent(jtxtDept, javax.swing.GroupLayout.DEFAULT_SIZE, 224, Short.MAX_VALUE))
                .addContainerGap())
        );
        jpnInsertLayout.setVerticalGroup(
            jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnInsertLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jlbTitulo)
                    .addComponent(jlbDept))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jtxtTitulo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jtxtDept, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jtbRemove.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane1.setViewportView(jtbRemove);

        jbtRemove.setText("Remover");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 496, Short.MAX_VALUE)
                            .addComponent(jpnInsert, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addContainerGap())
                    .addComponent(jbtRemove, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jpnInsert, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 196, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jbtRemove))
        );
    }// </editor-fold>//GEN-END:initComponents

    //Ação tomada quando o painel é apresentado ao usuário
    private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
        // TODO add your handling code here:
        try {
                // TODO add your handling code here:
                setupTable();
            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(null, "Não foi possível resgatar as informações da tabela");
                frame.printException(ex);
            }
    }//GEN-LAST:event_formComponentShown

    //Ação tomada ao clicar no painel com o mouse
    private void formMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseClicked
        // TODO add your handling code here:
        jtbRemove.clearSelection();
    }//GEN-LAST:event_formMouseClicked
            
    //configura as tabelas utilizadas na remoção a partir de dados adquiridos da base de dados
    public void setupTable() throws SQLException {

        String [] fields = {"comercial.idPr","comercial.tituloPr","comercial.descricaoPr",
            "comercial.idDe" };
        String [] titles = {"ID Comercial","Titulo","Descricao","ID Departamento"};
        String [] params = {"comercial.idDe=departamento.idDe"};
        String [][] result = dbInterface.view(fields,params,new String[]{"comercial","departamento"});

        DefaultTableModel model = new DefaultTableModel(result,titles);
        jtbRemove.setModel(model);

    }



    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton jbtRemove;
    private javax.swing.JLabel jlbDept;
    private javax.swing.JLabel jlbTitulo;
    private javax.swing.JPanel jpnInsert;
    private javax.swing.JTable jtbRemove;
    private javax.swing.JTextField jtxtDept;
    private javax.swing.JTextField jtxtTitulo;
    // End of variables declaration//GEN-END:variables

    //Ouvite de ação do botão de remoção
    class ComercialAction implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            ArrayList<String> param = new ArrayList<String>();

                if (jtxtTitulo.getText().trim().compareTo("") != 0) {
                    param.add("comercial.tituloPr='"+jtxtTitulo.getText()+"'");
                }
                if (jtxtDept.getText().trim().compareTo("") != 0) {
                    try {
                        String[][] s = dbInterface.view(new String[]{"idDe"}, 
                                new String[]{"UPPER(departamento.nomeDe)=UPPER('" + jtxtDept.getText() + "')"},
                                new String[]{"departamento"});
                        param.add("comercial.idDe="+s[0][0]);
                    } catch (SQLException ex) {
                        Logger.getLogger(CoRmPanel.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                //verifica se há algma condição na remoção escolhida nos campos da interface
                if (param.size() > 0) {
                    try {
                        String[] paramArray = new String[param.size()];
                        param.toArray(paramArray);
                        dbInterface.remove(paramArray, new String[]{"comercial"});
                    } catch (SQLException ex) {
                        frame.printException(ex);
                        JOptionPane.showMessageDialog(null, "Erro ao remover as tuplas desejadas.");
                    }
                    //senão remove utilizando a tabela da interface
                } else {

                    if (jtbRemove.getSelectedRowCount() > 1) {
                    JOptionPane.showMessageDialog(null, "Você deve selecionar apenas uma linha da tabela.");
                    }
                    else if (jtbRemove.getSelectedRowCount() == 1) {
                        try {
                            String[] params = new String[1];
                            params[0] = "idPr=" + jtbRemove.getValueAt(jtbRemove.getSelectedRow(), 0);
                            dbInterface.remove(params, new String[]{"comercial"});
                        } catch (SQLException ex) {
                            frame.printException(ex);
                            JOptionPane.showMessageDialog(null, "Erro ao tentar remover a tupla.");
                        }
                    }
                    else if (jtbRemove.getSelectedRowCount() == 0) {
                        JOptionPane.showMessageDialog(null, "Você deve escolhar uma tupla ou um parâmetro para a remoção.");
                    }
                }
            try {
                setupTable();
            } catch (SQLException ex) {
                frame.printException(ex);
            }

        }
    }


}
